const path = require('path');
const fs = require('fs');
const {
    hydrateProcessEnv,
    determineBackendPort,
    determineFrontendPort,
} = require('./env-utils');

function generateEnvironmentFile() {
    hydrateProcessEnv();

    const backendPort = determineBackendPort();
    const explicitApiBaseUrl = process.env.API_BASE_URL;

    let resolvedApiBase;
    // Use explicit API_BASE_URL if set to a non-localhost value (e.g., production/staging URLs)
    // This allows prod builds to use explicit URLs like http://ai.synergy:3000/api/
    if (explicitApiBaseUrl && !explicitApiBaseUrl.includes('localhost')) {
        resolvedApiBase = explicitApiBaseUrl;
    }
    // When running locally with dynamic ports, prioritize the runtime backend port
    else if (backendPort) {
        resolvedApiBase = `http://localhost:${backendPort}/api/`;
    }
    // Final fallback to explicit API_BASE_URL or default
    else {
        resolvedApiBase = explicitApiBaseUrl || 'http://localhost:3000/api/';
    }

    const frontPort = determineFrontendPort();
    const resolvedUiUrl = process.env.UI_URL || `http://localhost:${frontPort ?? '4200'}/`;

    const envVars = {
        version: process.env.npm_package_version,
        API_BASE_URL: resolvedApiBase,
        GCLOUD_PROJECT: process.env.GCLOUD_PROJECT,
        DATABASE_NAME: process.env.DATABASE_NAME,
        DATABASE_TYPE: process.env.DATABASE_TYPE,
        AUTH: process.env.AUTH,
        MODULES: process.env.MODULES,
    };

    console.log('[frontend env] configuration', { API_BASE_URL: envVars.API_BASE_URL, UI_URL: resolvedUiUrl });

    const environmentFile = `// This file is auto-generated by ${__filename}\nexport const env = ${JSON.stringify(envVars, null, 2)};\n`;

    const targetPath = path.join(__dirname, '../src/environments/.env.ts');

    try {
        fs.writeFileSync(targetPath, environmentFile);
        console.log(`Environment file generated successfully at ${targetPath}`);
    } catch (error) {
        console.error('Error generating environment file:', error);
        process.exit(1);
    }
}

generateEnvironmentFile();
